from django.shortcuts import render
from django.views.generic import View
from weasyprint import HTML
from django.http import HttpResponse
#import pdfkit
from django.template.loader import get_template
from django.template import Context
from xhtml2pdf import pisa
from io import BytesIO

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    print(type(html))
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
    if not pdf.err:
        return result.getvalue()
         # return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

# Create your views here.
class PDFExportView(View):
    def get(self, request, *args, **kwargs):
        data = dict(
                paper_title='大中文',
                sub_title='从德国来的装配经理马丁这几天频频竖起大拇指：中国协作团队的工作效率太让他惊讶了！',
                content="""马丁受雇于“金牛座”龙门铣的生产方德国瓦德里希科堡公司，他的工作职责是把首届中国国际进口博览会最大的展品“金牛座”龙门铣装配好，准时亮相展会。从“金牛座”抵达上海港，就一直在以“加速度”向展会奔去：查验、通关、运输到馆、开箱......处处体现进口博览会速度。"""
            )
        # content = render(request, 'pad/download-template.html', {"object": data}).content.decode()
        template = get_template('pad/download-template.html')
        html = template.render({"object": data})
        # print(content)
        # pdfkit.from_string('从德国来的装配经理马丁这几天频频竖起大拇指：中国协作团队的工作效率太让他惊讶了', './out.pdf')
        pdf = HTML(string=html).write_pdf('./test.pdf')
        # response = HttpResponse(pdf, content_type='application/pdf')
        # response['Content-Disposition'] = 'attachment; filename="{filename}.pdf"'.format(filename=data['paper_title'])
        # response.write(pdf)
        # return response
        return HttpResponse(html)

# class HeadlessPdfKit(pdfkit.PDFKit):
#     def command(self, path=None):
#         return ['xvfb-run', '--'] + super().command(path)


class NewPDFView(View):
    def get(self, request, *args, **kwargs):
        data = dict(
                paper_title='大中文',
                sub_title='从德国来的装配经理马丁这几天频频竖起大拇指：中国协作团队的工作效率太让他惊讶了！',
                content="""马丁受雇于“金牛座”龙门铣的生产方德国瓦德里希科堡公司，他的工作职责是把首届中国国际进口博览会最大的展品“金牛座”龙门铣装配好，准时亮相展会。从“金牛座”抵达上海港，就一直在以“加速度”向展会奔去：查验、通关、运输到馆、开箱......处处体现进口博览会速度。"""
            )
        # template = get_template('pad/download-template.html')
        # pdf = render_to_pdf('pad/download-template.html', {"object": data})
        # response = HttpResponse(content_type='application/pdf')
        # response['Content-Disposition'] = 'attachment; filename="{filename}.pdf"'.format(filename=data['paper_title'])
        template = get_template('pad/download-template.html')
        html = template.render({"object": data})
        with open('./haha.pdf', 'w+b') as f:
            pisa_status = pisa.CreatePDF(html, dest=f)
        # response.write(pdf)
        # return response

        return HttpResponse('ok')